package com.ids.redis;

import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.rapidoid.http.Req;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.Tuple;

import java.util.*;

/**
 * Created by sagnitude on 12/30/2015.
 */
public class ListAd {

    private static Gson gson;

    static {
        gson = new Gson();
    }

    public static List<String> getAdString(String endUserSn, int triggerType, String appToken, String jsonBeacons) {
        JedisCluster cluster = RedisConn.getInstance().getCluster();

        jsonBeacons = new String(Base64.getDecoder().decode(jsonBeacons.getBytes()));

        List<RssiRecord> results = gson.fromJson(jsonBeacons,
                new TypeToken<List<RssiRecord>>(){}.getType());

        Collections.sort(results, new Comparator<RssiRecord>() {
            @Override
            public int compare(RssiRecord o1, RssiRecord o2) {
                Integer i1 = o1.getRssi();
                Integer i2 = o2.getRssi();
                return i2.compareTo(i1);
            }
        });

        List<String> posIds = new ArrayList<String>();

        for (RssiRecord beacon : results) {
            String ret = cluster.get("UMM:POSID:" + beacon.getProximityUuid().toUpperCase()
                    + ":" + beacon.getMajor() + ":" + beacon.getMinor());
            if (ret != null) {
                posIds.add(ret);
            }
        }

        List<String> planIds = new ArrayList<String>();

        for (String posId : posIds) {
            Set<Tuple> ret = cluster.zrangeWithScores("POSID:PLANID:" + posId, 0, -1);
            if (ret != null) {
                for (Object tuple : ret) {
                    planIds.add(((Tuple) tuple).getElement());
                }
            }
        }

        List<String> adStrings = new ArrayList<String>();

        for (String planId : planIds) {
            String ret = cluster.get("ADPLAN:ADC:" + planId);
            if (ret != null) {
                adStrings.add(ret);
            }
        }

        return adStrings;
    }
}
